﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Windows.Forms.DataVisualization.Charting;

namespace 软构大作业
{
    public partial class Form13 : Form
    {
        private new AutoAdaptWindowsSize AutoSize;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private Data dao = new Data();
        private Color _seriesColor; // 存储随机生成的颜色
        private readonly Color[] _pieColors = {
            Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Purple,
            Color.Yellow, Color.Pink, Color.Cyan, Color.Magenta, Color.Lime
        };
        public Form13()
        {
            InitializeComponent();
            _seriesColor = GetRandomColor(); // 生成随机颜色
            InitializeChart();
            LoadChartData();
            LoadPieChartData(); // 加载扇形图数据
        }

        private void InitializeChart()
        {
            // 设置图表样式
            chart1.Series[0].ChartType = SeriesChartType.Bar;
            chart1.Series[0].Color = _seriesColor; // 使用随机颜色

            // 设置图表区域
            ChartArea chartArea = chart1.ChartAreas[0];

            // 调整X轴（数值轴）
            chartArea.AxisX.Interval = 1;
            chartArea.AxisX.LabelStyle.Font = new Font("Microsoft YaHei", 8f);
            chartArea.AxisX.Title = "借阅次数";

            // 调整Y轴（分类轴）
            chartArea.AxisY.LabelStyle.Font = new Font("Microsoft YaHei", 8f);
            chartArea.AxisY.LabelAutoFitMinFontSize = 6;
            chartArea.AxisY.LabelAutoFitMaxFontSize = 10;
            chartArea.AxisY.IsLabelAutoFit = true;
            chartArea.AxisY.LabelStyle.Angle = 0; // 水平显示标签

            // 设置图表边距
            chartArea.Position.Auto = false;
            chartArea.Position.X = 15;  // 左边距
            chartArea.Position.Y = 10;  // 上边距
            chartArea.Position.Width = 80;  // 宽度百分比
            chartArea.Position.Height = 85; // 高度百分比

            // 设置3D效果增加可读性
            chartArea.Area3DStyle.Enable3D = true;
            chartArea.Area3DStyle.Inclination = 15;
            chartArea.Area3DStyle.PointDepth = 100;

            // 设置标题样式
            if (chart1.Titles.Count == 0)
            {
                chart1.Titles.Add("图书借阅统计");
            }
            chart1.Titles[0].Font = new Font("Microsoft YaHei", 10f, FontStyle.Bold);

            // 设置数据点标签
            chart1.Series[0].IsValueShownAsLabel = true;
            chart1.Series[0].LabelForeColor = Color.Black;
            chart1.Series[0].LabelFormat = "0";
            chart1.Series[0].Font = new Font("Microsoft YaHei", 8f);
            // 扇形图设置（基于chart1._0代码）
            chart2.Series[0].ChartType = SeriesChartType.Pie;
            chart2.Series[0].BorderWidth = 1;
            chart2.Series[0].Label = "#PERCENT{P1}";
            chart2.Series[0].LegendText = "#VALX";
            chart2.Series[0].ToolTip = "#VALX: #VALY (#PERCENT)";

            // 图表区域设置
            chart2.ChartAreas[0].Area3DStyle.Enable3D = true;
            chart2.ChartAreas[0].Area3DStyle.Inclination = 30;
            chart2.ChartAreas[0].Area3DStyle.Rotation = 10;

            // 添加图例
            if (chart2.Legends.Count == 0)
            {
                chart2.Legends.Add(new Legend());
            }
            chart2.Legends[0].Docking = Docking.Bottom;
            chart2.Legends[0].Alignment = StringAlignment.Center;
        }
        private void LoadPieChartData()
        {
            try
            {
                // 查询图书分类和借阅次数
                string sql = "SELECT category, SUM(borrow_count) as total_borrows " +
                             "FROM library_db.books " +
                             "WHERE category IS NOT NULL " +
                             "GROUP BY category " +
                             "ORDER BY total_borrows DESC";

                SqlDataReader reader = dao.read(sql);
                chart2.Series[0].Points.Clear();

                var categoryData = new Dictionary<string, int>();
                int totalBorrows = 0;

                while (reader.Read())
                {
                    string category = reader["category"].ToString();
                    int borrows = Convert.ToInt32(reader["total_borrows"]);

                    categoryData.Add(category, borrows);
                    totalBorrows += borrows;
                }
                reader.Close();
                dao.DaoClose();

                // 添加数据点到扇形图
                int colorIndex = 0;
                foreach (var item in categoryData)
                {
                    DataPoint point = new DataPoint();
                    point.SetValueY(item.Value);
                    point.Color = _pieColors[colorIndex % _pieColors.Length];
                    point.Label = $"{Math.Round((double)item.Value / totalBorrows * 100, 1)}%";
                    point.LegendText = $"{item.Key}: {item.Value}";
                    point.LabelToolTip = $"{item.Key}: {item.Value}次借阅";
                    chart2.Series[0].Points.Add(point);
                    colorIndex++;
                }

                // 更新图表标题
                if (chart2.Titles.Count == 0)
                {
                    chart2.Titles.Add("图书分类借阅统计");
                }
                chart2.Titles[0].Text = $"图书分类借阅统计 (共{categoryData.Count}类，总借阅{totalBorrows}次)";
                chart2.Titles[0].Font = new Font("Microsoft YaHei", 10f, FontStyle.Bold);

                chart2.Update();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载分类数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void LoadChartData()
        {
            try
            {
                string sql = "SELECT title, borrow_count FROM library_db.books WHERE borrow_count IS NOT NULL ORDER BY borrow_count DESC";
                SqlDataReader reader = dao.read(sql);

                chart1.Series[0].Points.Clear();

                int totalTimes = 0;
                int bookCount = 0;
                var bookData = new List<(string name, int times)>();

                while (reader.Read())
                {
                    string bookName = reader["title"].ToString();
                    int times = Convert.ToInt32(reader["borrow_count"]);

                    // 处理过长的书名 - 添加换行符
                    if (bookName.Length > 15)
                    {
                        bookName = InsertLineBreaks(bookName, 15);
                    }

                    bookData.Add((bookName, times));
                    totalTimes += times;
                    bookCount++;
                }
                reader.Close();
                dao.DaoClose();

                // 添加数据到柱状图
                foreach (var data in bookData)
                {
                    DataPoint barPoint = new DataPoint();
                    barPoint.SetValueXY(data.name, data.times);
                    barPoint.Color = _seriesColor;
                    barPoint.Label = data.times.ToString();
                    chart1.Series[0].Points.Add(barPoint);
                }

                // 更新图表标题
                if (chart1.Titles.Count > 0)
                {
                    chart1.Titles[0].Text = $"图书借阅统计 (共{bookCount}本，总借阅{totalTimes}次)";
                }

                // 自动调整图表大小
                chart1.Invalidate();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 辅助方法：在字符串中插入换行符
        private string InsertLineBreaks(string input, int maxLength)
        {
            StringBuilder result = new StringBuilder();
            int currentLength = 0;

            foreach (char c in input)
            {
                result.Append(c);
                currentLength++;

                if (currentLength >= maxLength && char.IsWhiteSpace(c))
                {
                    result.Append("\n");
                    currentLength = 0;
                }
            }

            return result.ToString();
        }

        private Color GetRandomColor()
        {
            Random rnd = new Random();
            return Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
        }
        //private void Form13_FormClosed(object sender, FormClosedEventArgs e)
        //{
        //    Global.Instance.form13login.Hide();
        //    Global.Instance.form7login.Show();
        //}

        private void button3_Click(object sender, EventArgs e)
        {
            Global.Instance.form13login.Hide();
            Global.Instance.form7login.Show();
        }

        private void Form13_FormClosed_1(object sender, FormClosedEventArgs e)
        {
            Global.Instance.form13login=null;
            Global.Instance.form7login.Show();
        }

        private void Form13_Load(object sender, EventArgs e)
        {
            AutoSize = new AutoAdaptWindowsSize(this);
            this.SizeChanged += new EventHandler(Form_SizeChanged);
        }
        private void Form_SizeChanged(object sender, EventArgs e)
        {//窗体大小改变事件
            if (AutoSize != null) // 一定加这个判断，电脑缩放布局不是100%的时候，会报错
            {
                AutoSize.FormSizeChanged();
            }
        }
    }
}



